package com.twotwoshop.service.search.service.Impl;


import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.goods.dtos.GoodsSearchDto;
import com.twotwoshop.domin.search.ApUserSearch;
import com.twotwoshop.domin.search.HistorySearchDto;
import com.twotwoshop.fegin.api.user.IUserClient;
import com.twotwoshop.service.search.service.GoodsHistoryService;
import com.twotwoshop.service.search.service.GoodsSearchService;
import com.twotwoshop.service.search.strategy.SearchGranter;
import com.twotwoshop.service.search.strategy.SearchImpl.GoodsSearchFactory;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;


@Service
@Slf4j
@RequiredArgsConstructor
public class GoodsHistoryServiceImpl implements GoodsHistoryService {

    private final MongoTemplate mongoTemplate;


    /**
     * 查询时记录搜索历史 保存用户搜索历史
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async("twotwoExecutor")
    public void insert(String keyword, Integer userId) {

        log.info("保存用户搜索记录");

        //参数判空 用户搜索词为空 什么都不做
        if (StringUtils.isBlank(keyword) || userId==null) {
            return;
        }

        //1.查询用户搜索历史记录
        //封装查询条件Query
        Query query = new Query(Criteria.where("userId").is(userId).and("keyword").is(keyword));

        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在，更新创建时间
        if (apUserSearch!=null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3.不存在 添加新的搜索记录
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        //按时间倒叙排序搜素记录
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        //不超过10条 直接添加
        if (apUserSearchList!=null&&apUserSearchList.size()<5) {
            mongoTemplate.save(apUserSearch);
        }else {
            //超过 替换最早的记录

            //先查询最早的一条记录
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);

            //查询并替换最新记录
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), apUserSearch);

        }

    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {

        //获取当前用户
        Long userId = Long.valueOf(AppThreadLocalUtil.getUser().getId());

        if (userId==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //根据用户查询  按照时间倒序
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId")
                        .is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);


        return ResponseResult.okResult(apUserSearches);
    }



    /**
     * 删除搜索历史
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult removeUserSearch(HistorySearchDto historySearchDto) {
        //1.判断参数是否为空
        if (historySearchDto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }


        //2.判断当前用户是否登录
        Long userId = AppThreadLocalUtil.getUser().getId().longValue();

        if (userId==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询当前记录是否存在
        ApUserSearch search = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)
                .and("id").is(historySearchDto.getId())), ApUserSearch.class);

        if (search==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该历史记录不存在");
        }

        //3.根据历史记录id删除记录
        try {
            mongoTemplate.remove(search);
        } catch (Exception e) {
            log.error(e.getMessage(),"删除历史搜索记录失败");
            throw new RuntimeException(e);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




































